package com.asiainfo.service;
/*
 * 
 * 消费信息service
 */
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import com.asiainfo.bean.Card;
import com.asiainfo.bean.Consume;
import com.asiainfo.bean.VIP;
import com.asiainfo.dao.Consume_Dao;

public class ConsumeService {
	// 消费一次
	Logger logger = Logger.getLogger("");
	public void consume(String[] args) {
		if (args.length != 2) {
			logger.warning("对不起，请输入合法参数");
			System.out.println("对不起，请输入合法参数");
			return;
		}
		VipService vs = new VipService();
		VIP vip = vs.findVipByName(args[1]);
		//判断消费的用户是否存在
		if (vip != null) {
			CardService cs = new CardService();
			List<Card> cards = cs.findUsingCardsByVipId(vip.getId());
			//判断用户是否有已经激活的卡
			if (cards.size() == 0) {
				logger.warning("对不起，您还未绑定任何卡");
				System.out.println("对不起，您还未绑定任何卡");
			} else {
				//去消费
				int consume_result = consume(cards.get(0).getId());
				if (consume_result == 0) {
					System.out.println("消费成功");
				} else if (consume_result == 1) {
					System.out.println("您的卡已过期，已自动为您激活一张年卡");
				} else if (consume_result == 2) {
					System.out.println("您的卡已过期，已自动为您激活一张年卡");
				} else {
					logger.warning("对不起，您的卡已过期");
					System.out.println("对不起，您的卡已过期");
				}
			}
		} else {
			logger.warning("对不起，您所指定的用户不存在");
			System.out.println("对不起，您指定的用户不存在");
		}
	}
	//增加消费信息
	public void add(Consume consume){
		Consume_Dao cd = new Consume_Dao();
		cd.add(consume);
	}
	// 消费一次
	public int consume(int card_id) {
		CardService cs = new CardService();
		Card card = cs.findCardById(card_id);
		//判断用户当前激活的卡是否有效
		if (cs.justcarduserable(card)) {
			Consume consume = new Consume((int) new Date().getTime(), card_id);
			add(consume);
			if (card.getType() == 2) {
				card.setNum(card.getNum() - 1);
				cs.updatecard(card);
			}
			return 0;
		} else {
			card.setState(3);
			cs.updatecard(card);
			//查找用户所有备用的卡
			List<Card> cards = cs.findCardsByVipId(card.getVip_id());
			if (cards.size() != 0) {
				//如果有备用的卡
				card = cards.get(0);
				Consume consume = new Consume((int) new Date().getTime(), card.getId());
				add(consume);
				if (card.getType() == 2) {
					card.setNum(card.getNum() - 1);
				}
				card.setDate((int) new Date().getTime());
				//激活卡
				card.setState(2);
				cs.updatecard(card);
				return card.getType();
			}
			return -1;
		}
	}
}
